package org.jeecg.modules.wlhy.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.DateUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;
import java.util.UUID;

/**
 * @author duanlikao
 */
@Slf4j
public class NewWaterMarkUtils {

    private static String FONT_PATH = "font/simsun.ttf";//宋体

    // 水印透明度 1 最强，不透明 0 最弱，透明的。
    private static final float alpha = 0.5f; //0.5
    /**
     * 水印之间的横向间隔
     */
    private static final int XMOVE = 0;

    /**
     * 水印之间的纵向间隔
     */
    private static final int YMOVE = 0;



    public static Font  getDefinedFont(float fs) {

        Font definedFont = null;
        InputStream is = null;
        BufferedInputStream bis = null;
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try (InputStream stream = loader.getResourceAsStream(FONT_PATH)) {
            bis = new BufferedInputStream(stream);
            definedFont = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(Font.PLAIN,fs);
        } catch (FontFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != bis) {
                    bis.close();
                }
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        System.out.println("definedFont:"+definedFont);
        return definedFont;
    }

    /**
     * 图片添加水印
     *
     * @param outImgPath       添加水印后图片输出路径
     * @param markContentColor 水印文字的颜色
     * @param fontSize         文字大小
     * @param waterMarkContent 水印的文字,多排水印请使用"||"分割
     * @param srcImgPath       需要添加水印的图片的路径
     */
    public static  String waterPress(String srcImgPath, String outImgPath, Color markContentColor, int fontSize, String waterMarkContent) {
//        log.info("waterPress srcImgPath:{} waterMarkContent :{}",srcImgPath , waterMarkContent);

        String dateString = DateUtils.dateToStringDateTime(new Date());
        String uid =  UUID.randomUUID().toString().replace("-", "");
        String imgWithWatermarkFileName = "watermark_"+dateString+"_"+uid+".jpg" ;

        try {
            String[] waterMarkContents = waterMarkContent.split("\\|\\|");
            // 读取原图片信息
            File srcImgFile = new File(srcImgPath);
            Image srcImg = ImageIO.read(srcImgFile);
            // 原图宽度
            int srcImgWidth = srcImg.getWidth(null);
            // 原图高度
            int srcImgHeight = srcImg.getHeight(null);
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            // 得到画笔对象
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);

            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            // 获取其中最长的文字水印的大小
            int maxLen = 0;
            int maxHigh = 0;
            for (int i = 0; i < waterMarkContents.length; i++) {
                waterMarkContent = waterMarkContents[i];
                int fontlen = getWatermarkLength(waterMarkContent, g);
                if (fontlen >= maxLen) {
                    maxLen = fontlen;
                }
                maxHigh = maxHigh + (i + 1) * fontSize + 10;
            }

            //横屏图片使用默认
            //竖屏图片|正方形图片|图片宽度小于水印字体长度 计算字体大小
            if(srcImgWidth < srcImgHeight || srcImgWidth == srcImgHeight || srcImgWidth < maxLen ){
                fontSize = (int) Math.round(srcImgWidth*0.037);
            }
//            System.out.println(srcImgWidth+"======"+maxLen+"======"+fontSize);
            // Font font = new Font("Courier New", Font.PLAIN, 12);
            // 字体
//            Font font = new Font("宋体", Font.PLAIN, fontSize);
            Font font = getDefinedFont(fontSize);

            // 根据图片的背景设置水印颜色
            g.setColor(markContentColor);
            // 设置水印文字字体
            g.setFont(font);
            // 设置水印旋转
//            g.rotate(Math.toRadians(-45), (double) bufImg.getWidth() / 2, (double) bufImg.getHeight() / 2);


            // 文字长度相对于图片宽度应该有多少行
            int line = srcImgWidth * 2 / maxLen;
            int yz = 0;
                int t = 0;
                for (int j = 0; j < waterMarkContents.length; j++) {
                    waterMarkContent = waterMarkContents[j];
                    int y = (j + 1) * fontSize + 10 + t;

                    // 文字叠加,自动换行叠加，注意符号
                    int tempX = 20;
                    int tempY = (srcImgHeight - (150+fontSize)) + y + yz;

                    // 单字符长度
                    int tempCharLen = 0;
                    // 单行字符总长度临时计算
                    int tempLineLen = 0;
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < waterMarkContent.length(); i++) {
                        char tempChar = waterMarkContent.charAt(i);
                        tempCharLen = getCharLen(tempChar, g);
                        tempLineLen += tempCharLen;

                        // 和图片的长度进行对应的比较操作
                        if (tempLineLen >= (srcImgWidth-20)){
                            // 长度已经满一行,进行文字叠加
                            g.drawString(sb.toString(), tempX, tempY);
                            t = t + fontSize;
                            // 清空内容,重新追加
                            sb.delete(0, sb.length());
                            tempY += fontSize;

                            tempLineLen = 0;
                        }
                        // 追加字符
                        sb.append(tempChar);
                    }
                    // 填充X轴
                    for (int z = 0; z < line; z++) {
                        // 最后叠加余下的文字
                        g.drawString(sb.toString(), tempX, tempY);
                    }
                }

            g.dispose();
            File file = new File(outImgPath);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            // 输出图片
            FileOutputStream outImgStream = new FileOutputStream(outImgPath+ "/" + imgWithWatermarkFileName);
            ImageIO.write(bufImg, "jpg", outImgStream);
            outImgStream.flush();
            outImgStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        File fileTmp = new File(outImgPath + "/" + imgWithWatermarkFileName);
        return  fileTmp.exists() ? outImgPath + "/" + imgWithWatermarkFileName : StringUtils.EMPTY  ;
    }

    public static int getCharLen(char c, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charWidth(c);
    }

    /**
     * 获取水印文字总长度
     *
     * @paramwaterMarkContent水印的文字
     * @paramg
     * @return水印文字总长度
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }


    public static void main(String[] args) {
//        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
//        try (InputStream stream = loader.getResourceAsStream(FONT_PATH)) {
//            Font font = Font.createFont(Font.TRUETYPE_FONT, stream);
//            System.out.println("Font: " + font);
//            //Font的大小
//            font.deriveFont(18);
//            System.out.println("Font1: " + font);
//        } catch (FontFormatException | IOException ex) {
//            System.out.println(ex.getMessage());
//            // Logger.getLogger(FontLoader.class.getName()).log(Level.SEVERE, null, ex);
//        }


//        try {
//            final Font font = Font.createFont(Font.TRUETYPE_FONT, new BufferedInputStream(new FileInputStream(FONT_PATH)))
//                    .deriveFont(Font.PLAIN, 18);
//            System.out.println("Font:"+font);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        // 原图位置, 输出图片位置, 水印文字颜色, 水印文字
        String font = "2022-06-08 04:52:39||山西省太原市尖草坪区太原北服务区太原市跃盛工贸有限公司";

        String url = NewWaterMarkUtils.waterPress("/Users/duanlikao/Downloads/case_model.png",
                "/Users/duanlikao/Downloads", Color.GRAY, 25, font);
        System.out.println(url);
    }
}
